'''
Author: SlytherinGe
LastEditTime: 2021-04-01 10:01:52
'''

import logging

import torch
import torch.nn as nn
from mmcv.cnn import ConvModule, constant_init, kaiming_init
from mmcv.runner import load_checkpoint
from torch.nn.modules.batchnorm import _BatchNorm


if __name__ == '__main__':
    from mmdet.models.builder import BACKBONES
else:
    from ..builder import BACKBONES


class ResBlock(nn.Module):
    """The basic residual block used in TwoWay_Darknet. Each ResBlock consists of two
    ConvModules and the input is added to the final output. Each ConvModule is
    composed of Conv, BN, and LeakyReLU. In YoloV3 paper, the first convLayer
    has half of the number of the filters as much as the second convLayer. The
    first convLayer has filter size of 1x1 and the second one has the filter
    size of 3x3.

    Args:
        in_channels (int): The input channels. Must be even.
        conv_cfg (dict): Config dict for convolution layer. Default: None.
        norm_cfg (dict): Dictionary to construct and config norm layer.
            Default: dict(type='BN', requires_grad=True)
        act_cfg (dict): Config dict for activation layer.
            Default: dict(type='LeakyReLU', negative_slope=0.1).
    """

    def __init__(self,
                 in_channels,
                 conv_cfg=None,
                 norm_cfg=dict(type='BN', requires_grad=True),
                 act_cfg=dict(type='LeakyReLU', negative_slope=0.1)):
        super(ResBlock, self).__init__()
        assert in_channels % 2 == 0  # ensure the in_channels is even
        half_in_channels = in_channels // 2

        # shortcut
        cfg = dict(conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg)

        self.conv1 = ConvModule(in_channels, half_in_channels, 1, **cfg)
        self.conv2 = ConvModule(
            half_in_channels, in_channels, 3, padding=1, **cfg)

    def forward(self, x):
        residual = x
        out = self.conv1(x)
        out = self.conv2(out)
        out = out + residual

        return out


@BACKBONES.register_module()
class TwoWay_Darknet(nn.Module):
    """TwoWay_Darknet backbone.

    Args:
        depth (int): Depth of TwoWay_Darknet. Currently only support 53.
        out_indices (Sequence[int]): Output from which stages.
        frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
            -1 means not freezing any parameters. Default: -1.
        conv_cfg (dict): Config dict for convolution layer. Default: None.
        norm_cfg (dict): Dictionary to construct and config norm layer.
            Default: dict(type='BN', requires_grad=True)
        act_cfg (dict): Config dict for activation layer.
            Default: dict(type='LeakyReLU', negative_slope=0.1).
        norm_eval (bool): Whether to set norm layers to eval mode, namely,
            freeze running stats (mean and var). Note: Effect on Batch Norm
            and its variants only.

    Example:
        >>> from mmdet.models import TwoWay_Darknet
        >>> import torch
        >>> self = TwoWay_Darknet(depth=53)
        >>> self.eval()
        >>> inputs = torch.rand(1, 3, 416, 416)
        >>> level_outputs = self.forward(inputs)
        >>> for level_out in level_outputs:
        ...     print(tuple(level_out.shape))
        ...
        (1, 256, 52, 52)
        (1, 512, 26, 26)
        (1, 1024, 13, 13)
    """

    # Dict(depth: (layers, channels))
    arch_settings = {
        53: ((1, 2, 8, 8, 4), ((32, 64), (64, 128), (128, 256), (256, 512),
                               (512, 1024)))
    }

    def __init__(self,
                 depth=53,
                 in_channels=3,
                 out_indices=(3, 4, 5),
                 frozen_stages=-1,
                 conv_cfg=None,
                 norm_cfg=dict(type='BN', requires_grad=True),
                 act_cfg=dict(type='LeakyReLU', negative_slope=0.1),
                 norm_eval=True):
        super(TwoWay_Darknet, self).__init__()
        if depth not in self.arch_settings:
            raise KeyError(f'invalid depth {depth} for TwoWay_Darknet')
        self.depth = depth
        self.out_indices = out_indices
        self.frozen_stages = frozen_stages
        self.layers, self.channels = self.arch_settings[depth]

        cfg = dict(conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg)

        self.conv1 = ConvModule(in_channels, 32, 3, padding=1, **cfg)
        self.conv2 = ConvModule(in_channels, 32, 3, padding=1, **cfg)

        self.cr_blocks = ['conv1', 'conv2']
        self.fus_layers = []
        for i, n_layers in enumerate(self.layers):
            in_c, out_c = self.channels[i]
            for j in range(2):
                layer_name = f'conv{j + 1}_res_block{i + 1}'
                self.add_module(
                    layer_name,
                    self.make_conv_res_block(in_c, out_c, n_layers, **cfg))
                self.cr_blocks.append(layer_name)
            if i+1 in self.out_indices:
                fusion_layer = ConvModule(out_c*2,
                                            out_c,
                                            kernel_size=1,
                                            stride=1,
                                            padding=0,
                                            **cfg)
                fusion_name = f'fusion{i+1}'
                self.add_module(fusion_name, fusion_layer)
                self.fus_layers.append(fusion_name)

        self.norm_eval = norm_eval

    def forward(self, x):
        # split six channal x into two three channel data
        middle_data = [x[:,:3,:,:], x[:,3:,:,:]]
        outs = []
        real_outs = []
        for i, layer_name in enumerate(self.cr_blocks):
            path_id = i % 2
            indice = i // 2
            cr_block = getattr(self, layer_name)
            middle_data[path_id] = cr_block(middle_data[path_id])
            if indice in self.out_indices:
                outs.append(middle_data[path_id])

        for i, layer_name in enumerate(self.fus_layers):
            fus_layer = getattr(self, layer_name)
            feature_out = fus_layer(torch.cat([outs[i*2],outs[i*2+1]], dim=1))
            real_outs.append(feature_out)            

        return tuple(real_outs)

    def init_weights(self, pretrained=None):
        if isinstance(pretrained, str):
            logger = logging.getLogger()
            load_checkpoint(self, pretrained, strict=False, logger=logger)
        elif pretrained is None:
            for m in self.modules():
                if isinstance(m, nn.Conv2d):
                    kaiming_init(m)
                elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
                    constant_init(m, 1)

        else:
            raise TypeError('pretrained must be a str or None')

    def _freeze_stages(self):
        if self.frozen_stages >= 0:
            for i in range(self.frozen_stages):
                m = getattr(self, self.cr_blocks[2*i])
                m.eval()
                for param in m.parameters():
                    param.requires_grad = False
                n = getattr(self, self.cr_blocks[2*i+1])
                n.eval()
                for param in n.parameters():
                    param.requires_grad = False

    def train(self, mode=True):
        super(TwoWay_Darknet, self).train(mode)
        self._freeze_stages()
        if mode and self.norm_eval:
            for m in self.modules():
                if isinstance(m, _BatchNorm):
                    m.eval()

    @staticmethod
    def make_conv_res_block(in_channels,
                            out_channels,
                            res_repeat,
                            conv_cfg=None,
                            norm_cfg=dict(type='BN', requires_grad=True),
                            act_cfg=dict(type='LeakyReLU',
                                         negative_slope=0.1)):
        """In TwoWay_Darknet backbone, ConvLayer is usually followed by ResBlock. This
        function will make that. The Conv layers always have 3x3 filters with
        stride=2. The number of the filters in Conv layer is the same as the
        out channels of the ResBlock.

        Args:
            in_channels (int): The number of input channels.
            out_channels (int): The number of output channels.
            res_repeat (int): The number of ResBlocks.
            conv_cfg (dict): Config dict for convolution layer. Default: None.
            norm_cfg (dict): Dictionary to construct and config norm layer.
                Default: dict(type='BN', requires_grad=True)
            act_cfg (dict): Config dict for activation layer.
                Default: dict(type='LeakyReLU', negative_slope=0.1).
        """

        cfg = dict(conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg)

        model = nn.Sequential()
        model.add_module(
            'conv',
            ConvModule(
                in_channels, out_channels, 3, stride=2, padding=1, **cfg))
        for idx in range(res_repeat):
            model.add_module('res{}'.format(idx),
                             ResBlock(out_channels, **cfg))
        return model


if __name__ == '__main__':
    import torch
    net = TwoWay_Darknet(depth=53)
    # print(net)
    # net.train()
    # net.eval()
    # inputs = torch.rand(1, 6, 416, 416)
    # level_outputs = net.forward(inputs)
    # for level_out in level_outputs:
    #     print(tuple(level_out.shape))
    net.init_weights()
    state_dict = net.state_dict()
    torch.save(state_dict, '/media/gejunyao/Disk/Gejunyao/develop/temp/temp.pth')